#!/bin/bash -l
source /etc/profile
CONFIG_INI_FILE=$1

if ! [ -a "${CONFIG_INI_FILE}" ];
then
  echo "config not exist!"
  exit 1
fi

exportParams(){
  PARAM_FILE=$1
  ! [ -a ${PARAM_FILE} ] && return 1
  PARAMS=($(cat ${PARAM_FILE} | grep -v '#' | awk NF))
  for PARAM in "${PARAMS[@]}"
  do
    KEY=$(echo "${PARAM}" | awk -F '=' '{print $1}')
    VALUE=$(echo "${PARAM}" | awk -F '=' '{print $2}')
    eval "${KEY}=${VALUE}"
  done
}
exportParams ${CONFIG_INI_FILE}

if [ -n "$(java -version 2>&1 | grep "command not found")" ];
then
  echo "java command not found"
  exit 1
fi

#项目所要发布的位置
#jenkins-compiler生成的deploy位置
ARCHIVED_FILE_DIR="$([ ${REMOTE_DEPLOY} == YES ] && echo ${DEPLOY_POSITION_DIR} || echo ${PROJECT_DIR}/jenkins_deploy)/${DEPLOY_FILE_DIR_NAME}/archived"
OLD_IFS="$IFS";IFS=",";modules=(${modules});IFS="$OLD_IFS"

#DEPLOY_POSITION_DIR判断
if ! [ -d ${DEPLOY_POSITION_DIR} ];
then
  echo "${DEPLOY_POSITION_DIR} isn't exist,help you create it"
  mkdir -p ${DEPLOY_POSITION_DIR}
fi

#备份
if [ ${AUTO_BACKUP} == "YES" ];
then
  echo "start backups"
  for module in "${modules[@]}"
  do
    if ! [ -d ${ARCHIVED_FILE_DIR}/${module} ];
    then
      echo "not exist ${module}"
      continue
    fi
    echo "backups ${module}"
    ITEMS=($(ls "${DEPLOY_POSITION_DIR}/${module}" | grep "${module}"))
    if [ ${#ITEMS[@]} -le 0 ];
    then
      continue
    fi
    BK_DIR="${DEPLOY_POSITION_DIR}/${module}/$(date "+%Y.%m.%d")"
    mkdir -p "${BK_DIR}"
    /bin/cp -rf ${DEPLOY_POSITION_DIR}/${module}/${module}* "${BK_DIR}"
  done
fi

#覆盖旧版本
echo "overwrite old application"
for module in "${modules[@]}"
do
  if ! [ -d ${ARCHIVED_FILE_DIR}/${module} ];
  then
    echo "not exist ${module}"
    continue
  fi
  if ! [ -d ${DEPLOY_POSITION_DIR}/${module} ];
  then
    mkdir -p "${DEPLOY_POSITION_DIR}/${module}"
  fi
  /bin/cp -rf ${ARCHIVED_FILE_DIR}/${module}/${module}* "${DEPLOY_POSITION_DIR}/${module}"
done

#重启服务
echo "reboot service"
#循环检测服务并且停止
checkAndStop(){
  while true;
  do
    NEED_STOP_MODULES_PID=()
    for module in "${modules[@]}"
    do
#      COMMAND="java -jar -Dspring.config.location=${DEPLOY_POSITION_DIR}/${module}/${module}.properties ${DEPLOY_POSITION_DIR}/${module}/${module}.jar"
#      PID=$(ps -ef | grep "${COMMAND}" | grep -v 'grep' | awk '{print $2}')
      PID=$(ps -ef | grep "${module}.jar" | grep -v 'grep' | awk '{print $2}')
      if [ -n "${PID}" ];
      then
        NEED_STOP_MODULES_PID=("${PID}" ${NEED_STOP_MODULES_PID[@]})
      fi
    done

    if [ ${#NEED_STOP_MODULES_PID[@]} -eq 0 ];
    then
      echo "need stop pid not found!"
      break
    fi

    #停止服务
    echo "need kill pids: ${NEED_STOP_MODULES_PID[*]}"
    kill -15 "${NEED_STOP_MODULES_PID[@]}"

    sleep 10
  done
}
checkAndStop


##启动服务
echo "begin start service"
BUILD_ID=DONTKILLME
CURRENT_DIR=$(pwd)
for module in "${modules[@]}"
do
  if ! [ -d ${ARCHIVED_FILE_DIR}/${module} ];
  then
    echo "not exist ${module}"
    continue
  fi
  cd "${DEPLOY_POSITION_DIR}/${module}" || exit
  echo "start ${module}"
  startedFlag=0
  nohup java -jar -Dspring.config.location=${DEPLOY_POSITION_DIR}/${module}/${module}.properties ${DEPLOY_POSITION_DIR}/${module}/${module}.jar > /dev/null 2>&1 &
  START_TIME=$(date "+%H:%M:%S" | awk -F ':' '{print $1*60*60+$2*60+$3}')
  sleep 1
  #判断是否为链式启动 如果为链式启动检测启动状态
  if [ ${CHAIN_START} == YES ];
  then
    #检测是否启动成功
    count=0
    LOGS_DIR=${DEPLOY_POSITION_DIR}/${module}/tomcat/logs
    for (( ; count<=${START_TIMEOUT}; count+=10 ))
    do
      if [ -d ${LOGS_DIR} ];
      then
        sleep 10
        CURRENT_TIME=$(date "+%H:%M:%S" | awk -F ':' '{print $1*60*60+$2*60+$3}')
        CURRENT_DATE=$(date "+%Y-%m-%d")
        logs=($(ls ${LOGS_DIR} | grep core.log.${CURRENT_DATE}))
        #读取log
        for log in "${logs[@]}"
        do
          if [ -n "$(cat ${LOGS_DIR}/${log} | grep -w 'Tomcat started' | grep -w "${CURRENT_DATE}" | awk  '{print $2}' | awk -F ':' '$1*60*60+$2*60+$3>='${START_TIME}'&&$1*60*60+$2*60+$3<='${CURRENT_TIME})" ];
          then
            startedFlag=1
            break;
          fi
        done
        if [ ${startedFlag} -eq 1 ];
        then
          echo "${module} started！"
          break;
        else
          echo "${module} starting..."
        fi
      fi
    done
    #检测是否启动超时
    if [ ${startedFlag} -ge 0 ] && [ ${count} -ge ${START_TIMEOUT} ];
    then
      echo "start ${module} timeout, maybe start failed!"
      if [ ${CHAIN_START_ATOMICITY} == YES ];
      then
          checkAndStop
      fi
    fi
  fi
done
cd "${CURRENT_DIR}" || exit